#include "StdAfx.h"
#include "IOContainer.h"
#include "IOFInternal.h"
#include <process.h>
namespace IOFrame
{
	CIOContainer::CIOContainer(void)
	{
		m_hIOCP=CreateIoCompletionPort(INVALID_HANDLE_VALUE,
			NULL,
			NULL,
			GetCPUCoreNum()*2);
		ASSERT(NULL!=m_hIOCP);

		HANDLE hWorkThread=(HANDLE)_beginthread(WorkThread,0,this);
		ASSERT(NULL!=hWorkThread);
		CloseHandle(hWorkThread);
	}

	CIOContainer::~CIOContainer(void)
	{
		CloseHandle(m_hIOCP);
		m_hIOCP=NULL;
	}

	BOOL CIOContainer::AddObject( CIOObject *o )
	{
		ASSERT(NULL!=o);
		HANDLE hIOCP=CreateIoCompletionPort(o->GetHandle(),m_hIOCP,(ULONG_PTR)o,0);
		if(hIOCP!=m_hIOCP)
		{
			OutputErrorMessageToDebugConsole();
			return FALSE;
		}
		
		return o->Begin();
	}

	void CIOContainer::WorkThread(LPVOID lpParam)
	{
		CIOContainer *pThis=(CIOContainer*)lpParam;
		DWORD dwNumberOfByteTransferred;
		CIOObject *pObj;
		PIOData pDat;
		while(1)
		{
			pObj=NULL;
			pDat=NULL;
			dwNumberOfByteTransferred=0u;
 			if(GetQueuedCompletionStatus(pThis->m_hIOCP,&dwNumberOfByteTransferred,(PULONG_PTR)&pObj,(LPOVERLAPPED*)&pDat,INFINITE))
 			{
				ASSERT(NULL!=pObj);
				ASSERT(NULL!=pDat);
				if(NULL!=pDat)
				{
					pDat->dwBufferLen=dwNumberOfByteTransferred;
				}
				BOOL bSuccessPerform=pObj->Perform(pDat);
				if(!bSuccessPerform)
				{
					TRACE(_T("Perform Return False\n"));
					pObj->PerformError();
				}
				else
				{
					;
				}
 			}
			else
			{
				ASSERT(NULL!=pObj);
				ASSERT(NULL!=pDat);
				BOOL bSuccessError=pObj->Error(pDat);
				if(bSuccessError)
				{
					;
				}
				else
				{
					;
				}
			}
			//Sleep(100);
// 			TCHAR szMsg[1001];
// 			SYSTEMTIME st;
// 			GetLocalTime(&st);
// 			_stprintf(szMsg,_T("%02d:%02d:%02d.%03d\n"),st.wHour,st.wMinute,st.wSecond,st.wMilliseconds);
// 			OutputDebugString(szMsg);
		}
	}
}

